package pers.cnzdy.tutorial.Chapter8_Message_Service.Section4_AsyncTask;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class TimeConsumingTask extends AsyncTask<String, Integer, String>
{
    static final String TAG = "TimeConsumingTask";

    // ProgressDialog pDialog;
    private Context     context;
    private ProgressBar progressBar;
    private TextView    textView;


    public TimeConsumingTask(Context ctx, ProgressBar pb, TextView tv)
    {
        progressBar = pb;
        textView = tv;
        context = ctx;
    }

    @Override
    protected void onPreExecute() {
        //pDialog.show();
        textView.setText("启动...");
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            int percent = 0;
            while (true) {
                percent = doTimeConsumingTask(percent);
                Log.d(TAG, Integer.toString(percent));
                publishProgress(percent);
                if (percent >= 100) {
                    break;
                }
            }
        } catch (Exception e) {
            return "出现异常";
        }
        return "finish";
    }

    @Override
    protected void onProgressUpdate(Integer... progresses) {
        //pDialog.setMessage("Downloaded " + values[0] + "%");

        progressBar.setProgress(progresses[0]);
        textView.setText("执行..." + progresses[0] + "%");
    }

    @Override
    protected void onPostExecute(String result) {
        //pDialog.dismiss();
//        textView.setText(result);
        if (result == "finish") {
            Toast.makeText(context, "任务完成",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "任务失败",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private int doTimeConsumingTask(int percent) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return percent + 1;
    }
}
